﻿using Corina.Common;
using Corina.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;

namespace Corina.Datamodel.Base
{
    [DataContract]
    public class DatamodelEntityBase : BaseClass
    {
        public DatamodelEntityBase()
        {
            InitColumns();
        }

        #region Properties
        public virtual string TableName
        {
            get
            {
                string name = EntityType.Name.Replace("Info", "");
                string[] upper = RegexHelper.GetUpperChar(name);
                foreach (string _char in upper)
                {
                    name = name.Replace(_char, "_" + _char.ToLower());
                }

                return "t" + name;
            }
        }

        public virtual string SqlQueryString
        {
            get
            {
                return string.Format("SELECT {0}.* FROM {1} AS {0}", TableName.ToLower(), TableName);
            }
        }

        public virtual string SqlInsertString
        {
            get
            {
                StringBuilder builder = new StringBuilder();
                builder.AppendFormat("INSERT INTO {0} (", TableName);

                string[] properties = Columns().Where(t => !t.IsPrimaryKey).Select(t => t.ColumnName).ToArray();

                builder.Append(string.Join(",", properties.Select(t => string.Format("[{0}]", t)).ToArray()));
                builder.Append(") VALUES(@" + string.Join(",@", properties) + ")");

                return builder.ToString();
            }
        }

        public virtual string SqlUpdateString
        {
            get
            {
                string[] paras = Columns().Where(t => !t.IsPrimaryKey && !t.WriteOnce).Select(t => string.Format("[{0}]=@{0}", t.ColumnName)).ToArray();
                return string.Format("UPDATE {0} SET {1} WHERE Id=@Id", TableName, string.Join(",", paras));
            }
        }

        public virtual string SqlDeleteString
        {
            get
            {
                return string.Format("DELETE FROM {0} WHERE Id=@Id ", TableName);
            }
        }

        public List<DatabaseColumn> Columns()
        {
            return InitColumns().ToList();
        }
        #endregion

        #region Methods
        protected virtual IEnumerable<DatabaseColumn> InitColumns()
        {
            return null;
        }

        #endregion
    }
}
